import axios from 'axios'
import React, { useState} from 'react'
import { withRouter,RouteComponentProps } from 'react-router-dom'
import {Input} from "antd-mobile";

import style from './index.module.css'

const {login,wechat,phoneLogin,otherLogin,info,log,send} = style

interface Iresult {
    flag:boolean,
    token?:string
}

function Login(props:RouteComponentProps){

    const [phone,setPhone] = useState('')
    const [code,setCode] = useState('')

    const reg = new RegExp(/^(13[0-9]|14[0-9]|15[0-9]|166|17[0-9]|18[0-9]|19[8|9])\d{8}$/)

    async function getVerificationCode(){
        if(reg.test(phone)){
            const result = await axios.get(`/api/getVerificationCode/${phone}`)
            alert(`验证码为${result.data}`)
            return
        }
        alert('请填写正确的手机号')
        
    }
    async function login_info() {
        if(code.length !== 6){
            alert('请填写正确验证码')
            return
        }
        const result = await axios.get(`/api/login?phone=${parseInt(phone)}&code=${code}`)
        const data = result.data as Iresult
        if(data.flag){
            localStorage.setItem('Authorization',data.token as string)
            props.history.push({pathname:'/home'})
        }else{
            alert('验证码错误')
        }

        
    }
    
    return (
        <div className={login}>
            <div className={phoneLogin}>
                <div className={log}>
                    <div>
                        <Input
                            placeholder='手机号'
                            value={phone}
                            onChange={val => {
                                setPhone(val)
                            }}
                        />
                    </div>
                    <div>
                        <Input
                            placeholder='验证码'
                            value={code}
                            onChange={val=>{
                                setCode(val)
                            }}
                        />
                        <p onClick={getVerificationCode} className={send}>发送验证码</p>
                    </div>
                </div>
                <div onClick={login_info} className={info}>登陆</div>
            </div>
            <div className={otherLogin}>
                <p>其他方式登陆</p>
                <div className={wechat}/>
            </div>
        </div>
    )
}
export default withRouter(Login)